<?php
/**
 * Category.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-13 19:15:10
 * @modified    2023-02-13 19:15:10
 *
 */

namespace App\Models\Product;

use App\Models\BaseModel;
use App\Repositories\Product\CategoryRepo;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class Category extends BaseModel
{
    protected $table = 'product_category';

    protected $fillable = [
        'parent_id',
        'name',
        'sort_order',
        'status',
        'create_user_id'
    ];

    protected $appends = [
        'create_time_format',
        'update_time_format',
        'parent_name'
    ];

    private $all;

    public function getCreateTimeFormatAttribute()
    {
        return Carbon::parse($this->create_time)->toDateTimeString();
    }

    public function getUpdateTimeFormatAttribute()
    {
        return Carbon::parse($this->update_time)->toDateTimeString();
    }

    public function getParentNameAttribute()
    {
        $parentId = $this->parent_id;
        if (!$parentId) {
            return '';
        }
        if (is_null($this->all)) {
            $all = DB::table('product_category')->get()->toArray();
            if (!count($all)) {
                $this->all = [];
            } else {
                $data = [];
                foreach ($all as $item) {
                    $data[] = collect($item)->toArray();
                }
                $this->all = $data;
            }
        }
        if (!$this->all) {
            return '';
        }
        $data = collect($this->all)->keyBy('id')->toArray();
        $parentData = $data[$parentId];
        return $parentData['name'] ?? '';
    }

    public function scopeWithName($query, $name)
    {
        return $query->where('name', 'like', "%{$name}%");
    }

    public function scopeWithStatus($query, $status)
    {
        return $query->where('status', $status);
    }
}